import pretty_midi
from pygame import mixer  # Load the popular external library
import time

# 创建一个新的 PrettyMIDI 对象
midi_data = pretty_midi.PrettyMIDI()

# 添加一个乐器，这里我们选择电吉他作为主要乐器
electric_guitar = pretty_midi.Instrument(program=25)  # Program 25 is Electric Guitar (jazz)

# 定义一些摇滚风格的音符
rock_riff = [
    {'note': 60, 'start': 0.0, 'end': 0.5},  # C4
    {'note': 64, 'start': 0.5, 'end': 1.0},  # E4
    {'note': 67, 'start': 1.0, 'end': 1.5},  # G4
    {'note': 69, 'start': 1.5, 'end': 2.0},  # A4
    {'note': 67, 'start': 2.0, 'end': 2.5},  # G4
    {'note': 64, 'start': 2.5, 'end': 3.0},  # E4
]

# 将音符添加到乐器中
for note in rock_riff:
    note = pretty_midi.Note(
        velocity=100, pitch=note['note'], start=note['start'], end=note['end'])
    electric_guitar.notes.append(note)

# 把乐器加入到 MIDI 数据中
midi_data.instruments.append(electric_guitar)

# 将 MIDI 文件保存为 'rock_riff.mid'
output_midi_file = 'rock_riff.mid'
midi_data.write(output_midi_file)
print(f"Created rock riff and saved to {output_midi_file}")

# 使用 pygame 播放刚刚创建的 MIDI 文件
mixer.init()
mixer.music.load(output_midi_file)
mixer.music.play()

# 等待音乐结束或用户中断
try:
    while mixer.music.get_busy():
        time.sleep(1)
except KeyboardInterrupt:
    print("Playback stopped by user.")
    mixer.music.stop()
